package top.ffhome.system.controller;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import top.ffhome.common.result.Result;
import top.ffhome.system.entity.SysMenu;
import top.ffhome.system.service.SysMenuService;
import top.ffhome.util.bean.BeanUtil;

@CrossOrigin
@RestController
@RequestMapping("api/menu")
@Api(tags = "系统菜单控制器")
public class SysMenuController {
	@Autowired
	private SysMenuService menuService;

	@RequiresPermissions(value = { "system:role:view", "system:menu:view" }, logical = Logical.OR)
	@GetMapping("/getTree")
	@ApiOperation("获得菜单树状数据")
	public Result getTree() {
		return Result.success(menuService.getTree());
	}

	@RequiresPermissions("system:menu:edit")
	@PostMapping("/save")
	@ApiOperation("修改菜单")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "菜单ID", dataType = "Long", required = true, paramType = "body"),
			@ApiImplicitParam(name = "label", value = "菜单标签名称", dataType = "String", required = true, paramType = "body") })
	public Result save(@RequestBody SysMenu menu) {
		if (menu.getId() == null || menu.getId() == 0) {
			return Result.fail("参数不正确");
		}
		BeanUtil.constraintProperties(menu, CollUtil.newArrayList("id", "label"));
		menuService.update(menu);
		return Result.success();
	}

	@RequiresPermissions("system:menu:edit")
	@PostMapping("/move")
	@ApiOperation("将菜单ID移动到parentId中，序号为sort")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "待移动菜单ID", dataType = "Long", required = true, paramType = "body"),
			@ApiImplicitParam(name = "parentId", value = "移动目标的父ID", dataType = "Long", required = true, paramType = "body"),
			@ApiImplicitParam(name = "sort", value = "在父ID的次序", dataType = "Integer", required = true, paramType = "body") })
	public Result move(@RequestBody SysMenu menu) {
		if (ObjectUtil.isNull(menu.getId()) || ObjectUtil.isNull(menu.getParentId())
				|| ObjectUtil.isNull(menu.getSort())) {
			return Result.fail("参数不正确");
		}
		menuService.move(menu);
		return Result.success();
	}
}
